﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace QuaManSys.Rights
{
    public partial class RolesAuth : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["Id"] != null)
                {

                    RID.Text = Request.QueryString["Id"].ToString();
                    BindModules();
                }
                else
                {

                }

            }
            
        }

        /// <summary>
        /// 获取模块权限列表
        /// </summary>
        protected void BindModules()
        {
            using (QuaManSysEntities entity = new QuaManSysEntities())
            {
                var queryMenu = from q in entity.SysMenu
                                orderby q.Id
                                select q;

                ModuleView.DataSource = queryMenu.ToList();
                ModuleView.DataBind();

            }
        }

        protected void ModuleView_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)//DataRow行能绑定数据。
            {
                CheckBoxList AuthorityList_Grant = (CheckBoxList)e.Row.FindControl("AuthorityList_Grant");
                //CheckBoxList AuthorityList_Deny = (CheckBoxList)e.Row.FindControl("AuthorityList_Deny");
                Label lab_ID = (Label)e.Row.FindControl("lab_ID");
                Label lab_Verify = (Label)e.Row.FindControl("lab_Verify");
                //  AuthorityList_Grant.AutoPostBack = true;
                using (QuaManSysEntities entity = new QuaManSysEntities())
                {

                    var queryAllOper = from p in entity.SysOperation
                                       join q in entity.SysMenuSysOperation
                                       on p.Id equals q.SysOperationId
                                       where q.SysMenuId == lab_ID.Text
                                       orderby q.SysOperationId
                                       select p;

                    var queryRoleOper = from p in entity.SysOperation
                                        join q in entity.SysMenuSysRoleSysOperation
                                        on p.Id equals q.SysOperationId
                                        where q.SysMenuId == lab_ID.Text &&
                                            q.SysRoleId == RID.Text
                                        select p;
                        //from p in entity.SysRole
                        //                join q in entity.SysMenuSysRoleSysOperation
                        //                on p.Id equals q.SysRoleId
                        //                join r in queryAllOper
                        //                on q.SysOperationId equals r.Id
                        //                where p.Id == RID.Text
                        //                select r;
                    
                    int n = queryAllOper.Count();
                    if (n != 0)
                    {
                        bool[] vstate = new bool[n];
                        int i = 0;
                        bool roleSelected = false;
                        foreach (var item in queryAllOper)
                        {
                            foreach (var oper in queryRoleOper)
                            {
                                if (item == oper)
                                {
                                    roleSelected = true;
                                }
                            }
                            AuthorityList_Grant.Items.Add(new ListItem(item.Name, item.Id));
                            vstate[i] = roleSelected;//初始状态数组;
                            i++;
                            roleSelected = false;
                        }
                        for (i = 0; i < n; i++)
                        {
                            AuthorityList_Grant.Items[i].Selected = vstate[i];
                        }
                        AuthorityList_Grant.DataBind();
                        lab_Verify.Text = StringArrayToString(vstate, ',');
                    }
                }
            }

        }

        /// <summary>
        /// 将字符串数组转成字符串
        /// </summary>
        /// <param name="strArray">字符串数组</param>        
        /// <param name="Separator">分隔符</param>
        /// <returns>字符串</returns>
        public static string StringArrayToString(bool[] strArray, char Separator)
        {
            string str = string.Empty;
            string strbool;
            for (int i = 0; i < strArray.Length; i++)
            {
                if (strArray[i])
                    strbool = "1";
                else
                    strbool = "0";
                str = str + strbool + Separator;
            }
            return str.Substring(0, str.Length - 1);
        }

        protected void ModuleView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            ArrayList createRoleList = new ArrayList();//需要增加的权限
            ArrayList deleteRoleList = new ArrayList();//需要删除的权限

            CheckBoxList calg = (CheckBoxList)this.ModuleView.Rows[e.NewSelectedIndex].FindControl("AuthorityList_Grant");
            Label lab_Verify = (Label)this.ModuleView.Rows[e.NewSelectedIndex].FindControl("lab_Verify");
            Label lab_ID = (Label)this.ModuleView.Rows[e.NewSelectedIndex].FindControl("lab_ID");
            string[] vstate = lab_Verify.Text.Split(',');//获取原始状态

            for (int i = 0; i < calg.Items.Count; i++)
            {
                if (calg.Items[i].Selected)
                {
                    if (vstate[i] != "1")   //权限增加
                    {
                        createRoleList.Add(calg.Items[i].Value);
                    }
                }
                else
                {
                    if (vstate[i] != "0")   //权限删除
                    {
                        deleteRoleList.Add(calg.Items[i].Value);
                    }
                }
            }
            using (var entity = new QuaManSysEntities())
            {
                //权限增加
                foreach (var item in createRoleList)
                {
                    SysMenuSysRoleSysOperation newRoleMenuOper = new SysMenuSysRoleSysOperation()
                    {
                        SysOperationId = item.ToString(),
                        SysMenuId = lab_ID.Text,
                        SysRoleId = RID.Text
                    };

                    entity.SysMenuSysRoleSysOperation.Add(newRoleMenuOper);
                    entity.SaveChanges();
                }

                //权限删除
                foreach (var item in deleteRoleList)
                {
                    SysMenuSysRoleSysOperation delRoleOper =
                        (from c in entity.SysMenuSysRoleSysOperation
                         where c.SysOperationId == item.ToString() && c.SysMenuId == lab_ID.Text
                         && c.SysRoleId == RID.Text
                         select c).Single();
                    entity.SysMenuSysRoleSysOperation.Remove(delRoleOper);
                    entity.SaveChanges();
                }
            }
            BindModules();
        }

        protected void btn_AllSave_Click(object sender, EventArgs e)
        {
            //List<SysMenuSysRoleSysOperation> createRoleList = new List<SysMenuSysRoleSysOperation>();//需要增加的权限
            //List<SysMenuSysRoleSysOperation> deleteRoleList = new List<SysMenuSysRoleSysOperation>();//需要删除的权限
            for (int i = 0; i < ModuleView.Rows.Count; i++)
            {
                CheckBoxList calg = (CheckBoxList)this.ModuleView.Rows[i].FindControl("AuthorityList_Grant");
                Label lab_Verify = (Label)this.ModuleView.Rows[i].FindControl("lab_Verify");
                Label lab_ID = (Label)this.ModuleView.Rows[i].FindControl("lab_ID");
                string[] vstate = lab_Verify.Text.Split(',');//获取原始状态
                using (var entity = new QuaManSysEntities())
                {
                    for (int j = 0; j < calg.Items.Count; j++)
                    {
                        string roleId = calg.Items[j].Value;
                        if (calg.Items[j].Selected)
                        {
                            
                            if (vstate[j] != "1")   //权限增加
                            {
                                SysMenuSysRoleSysOperation newRoleMenuOper = new SysMenuSysRoleSysOperation()
                                {
                                    SysOperationId = roleId,
                                    SysMenuId = lab_ID.Text,
                                    SysRoleId = RID.Text
                                };
                                entity.SysMenuSysRoleSysOperation.Add(newRoleMenuOper);
                                entity.SaveChanges();
                            }
                        }
                        else
                        {
                            if (vstate[j] != "0")   //权限删除
                            {
                                var delRolesOper =
                                   (from c in entity.SysMenuSysRoleSysOperation
                                    where c.SysOperationId == roleId
                                        && c.SysMenuId == lab_ID.Text
                                        && c.SysRoleId == RID.Text
                                    select c).First();
                                entity.SysMenuSysRoleSysOperation.Remove(delRolesOper);
                                //foreach (var item in delRolesOper)
                                //{
                                    //entity.SysMenuSysRoleSysOperation.Remove(item);
                                //}
                                entity.SaveChanges();
                            }
                        }
                    }
                    //entity.SaveChanges();
                }

            }
            strinfo.Visible = true;
            RoleAuthMain.Visible = false;
        }
    }
}